package org.wak.inventory
{
	/**
	 *  This is the manager of the inventory Items of the adventure.
	 * 
	 */	
	public class InventoryManager
	{
		private var mItemsDefArray:Array = null ;
		private var mInventoryItemsArray:Array = null ;
		
		public function InventoryManager()
		{
			mItemsDefArray = new Array();
			mInventoryItemsArray = new Array();
		}
		
		/**
		 * Loads the Inventory Items's definition, but do not instanciate them . 
		 * @param pXMLItemsDef a XML object with the definition of the Inventory Items.
		 * 
		 */		
		public function LoadItemsDefinitions(pXMLItemsDef:XML):void
		{
			//mXmlItemsDefs = pXMLItemsDef ;
			ExtractInventoryItemsDefinitions(pXMLItemsDef,mItemsDefArray);
		}
		
		/**
		 * Get an InventoryItem by its id. 
		 * @param pItemId id of the InventoryItem
		 * @return InventoryItem
		 * 
		 */		
		public function GetInventoryItem(pItemId:String):InventoryItem
		{
			var fReturnItem:InventoryItem = null ;
			
			if( mInventoryItemsArray[ pItemId ] == null )
			{
				var fItemDef:IInventoryItemDefinition = mItemsDefArray[pItemId] as IInventoryItemDefinition ;
				if( fItemDef == null )
				{
					throw new Error("Unknown inventory item id: "+ pItemId);
				}
				else
				{
					mInventoryItemsArray[pItemId] = new InventoryItem(fItemDef);
					fReturnItem = mInventoryItemsArray[pItemId] as InventoryItem ;
				} 
			}
			else
			{
				fReturnItem = mInventoryItemsArray[pItemId] as InventoryItem ;
			}
			
			return fReturnItem ;
		}
		
		private function ExtractInventoryItemsDefinitions(pDefs:XML, pDest:Array):void
		{
			//trace("ExtractInventoryItemsDefinitions:"+pDefs.toXMLString())
			var fItemDef:IInventoryItemDefinition = null;
			for each( var def:XML in pDefs.IItem )
			{
				fItemDef = new XMLInventoryItemDefinition( def );
				pDest[fItemDef.itemId] = fItemDef ;
			}
		}

	}
}